﻿;(function(){
    $$.catalogTreeNode =  Ext.extend(Ext.tree.AsyncTreeNode, {
    	constructor: function(config, ItemTable){
    		
    		var storeObj = ItemTable.getStore();
    		ItemTable.catalogTreeNode = this;
    		this.loader = new Ext.tree.TreeLoader({
            	  directFn   : blogService.getCatalog
            	 ,baseParams : {
            	 	uiType : 'ext-direct-tree'
            	 }
            	 ,paramsAsHash : true
        	});

        	$$.catalogTreeNode.superclass.constructor.call(this, config);
        	this.on('click',  this.click,           storeObj);
        	
        	this.on('append', this.initNode,        storeObj);
        	this.on('load',   this.addHiddenNode,   storeObj);
        	this.on('load',   this.initContextMenu, storeObj);
        	
    	}
        ,text     : '浏览博贴'
        ,leaf     : false
        ,editable : false // False表示该节点不能够编辑的。
        ,action   : {
        	addCatalog : {
	        	 text    : '增加分类'
	        	,handler : function(){
	                var 
	                	 upperNode = this
	                	,newNode   = new Ext.tree.TreeNode({
					                    text:'新分类 ' 
					                });
		        		  
	                this.insertBefore(newNode, upperNode.hiddenCatalog);
	                // 登记节点的右键事件
	                newNode.on('contextmenu', upperNode.onNewNode_ContextMenu, upperNode);
	                 
	                // 创建新的节点之后，旋即提供一个编辑的状态，好让用户输入类别的名称。
	                // 向treeEditor报告我正在编辑的是什么 树节点
                    upperNode.treeEditor.editNode = newNode;
                    upperNode.treeEditor.startEdit(newNode.ui.textNode);
                    upperNode.treeEditor.isCreateCatalog = true;
                    
                  	upperNode.treeEditor.on('beforecomplete', function(treeEditor, newValueMix){
                  		if( treeEditor.isCreateCatalog === true){
						    var redoCB = function(reO){
				        		if(reO.isCreateCatalogOK === true){
					        		Ext.feedback.msg(Edk.config.appStr, "添加新类别{0}成功！".format(newValueMix));
				        		}else{
					                upperNode.treeEditor.editNode = newNode;
					                upperNode.treeEditor.startEdit(newNode.ui.textNode);
				        		}
			        		};
			        		blogService.addCatalog(encodeURIComponent(newValueMix), redoCB);
                  			treeEditor.isCreateCatalog = false;
                  		}
                  	});
	        	}
        	}
        	,delCatalog: {
				 text       : '删除分类'
		        ,iconCls    : 'icon16-delete'
		    	,handler    : function(){
		            var 
		            	 node    = this.getSelectedNodes()
		            	,showMsg = function(){
			                Ext.feedback.msg(Edk.config.tips,'“{0}”共{1}项删除完毕。'.format(textStr.substr(0, 20), i));
						}
		            	,msg     = "您确定xx删除<b>{0}</b>分类以下的<b>所有</b>记录？<br/>";
		  
		    		if(!node.length){
		    			Edk.Suite.Action.noSelected();
		    			return false;
		    		}else{
		    			node = node[0];
		    		}
					Ext.Msg.confirm(document.title, msg.format(node.text), function(btn){
		                if (btn != "yes") 
		                    return false;
		                blogService.del(idNum.pop ? idNum : [ idNum ], showMsg);
		            });
		        } 
        	}
        	,renameCatalog: function(editorObj, newValueMix, oldValueMix){
        		if(newValueMix != oldValueMix && !editorObj.isCreateCatalog){
	        		var idNum = this.getSelectedNodes()[0].attributes['ID'];
	        		var str   = '分类重命名成功！{1}-->{0}'.format(newValueMix, oldValueMix);
	        		blogService.renameCatalog(idNum, encodeURIComponent(newValueMix), function(reO){
		        		if(reO.renameOk  === true){
			        		Ext.feedback.msg(Edk.config.appStr, str);
		        		}else{
		        			this.setText(oldValueMix);
		        		}
	        		}, editorObj.editNode);;
        		}
        	}
        }

        ,click: function(catalogTreeNode){
        	catalogTreeNode.expand();
        	delete catalogTreeNode.loader.baseParams['ns'];
        	if(this.baseParams['ns']){
        		delete this.baseParams['ns'];
        		this.load();
        	}
        }
        ,initNode: function(treePanel, upperNode, newNode){
        	newNode.on('click', function(newNode){
        		var idNum    = newNode.attributes['ID'];
        		var storeObj = this;
        		// 同步Store刷新数据，指定属于该分类的数据显示
        		// @todo 多选
        		upperNode.loader.baseParams['ns'] = storeObj.baseParams['ns'] = idNum;
        		treePanel.expand();
        		storeObj.load();
        	}, this);
        	
        	// 每一个节点都要new一个Menu，N个节点怎么办！？
        	newNode.on('contextmenu', upperNode.onNewNode_ContextMenu, upperNode); 
        }
        ,onNewNode_ContextMenu : function(newNode, event){
    		event.preventDefault();
    		newNode.select();
    		var 
    			 hiddenNode  = newNode.attributes.action
    			,contextMenu = this.contextMenu
    			// 藉Class属性判断是“删除del”的Action
    			,delAction   = contextMenu.find('iconCls', 'icon16-delete')[0];
    		
    		// 如果遇到“隐藏”的那个大类，因为是特殊的分类，所以不能删除！	 
    		if(hiddenNode && hiddenNode == 'getHidden'){
    			delAction.disable();
    		}else{
    			delAction.enable();
    		}
    		contextMenu.showAt(event.getXY()); 
    	}
    	
        /*
         * 隐藏节点是一个固定的节点。
         */
        ,addHiddenNode: function(upperNode){
        	upperNode.hiddenCatalog = new Ext.tree.TreeNode({
        		text:'隐藏节点', leaf:true, iconCls:'icon16-trash', 
        			'action' : 'getHidden'
        	});
        	upperNode.appendChild(upperNode.hiddenCatalog);
        }
        ,initContextMenu : function(upperNode){
        	var 
        		 selModel   = upperNode.getOwnerTree().getSelectionModel()
        		,cataAction = upperNode.action
        		,delAction  = new Ext.Action(
	        		$$.apply({
						scope: selModel
		    	 	}, cataAction.delCatalog)
	    	 	)
	    	 	,addCatalog = new Ext.Action(
					$$.apply({
						scope: upperNode
					}, cataAction.addCatalog)
				);
				
        	upperNode.contextMenu = new Ext.menu.Menu({
			    items: [delAction, addCatalog]
			});
			// 初始化Node编辑器
			upperNode.treeEditor = new Ext.tree.TreeEditor(upperNode.getOwnerTree(), {/* fieldconfig here */ }, {
			     allowBlank    : false
			    ,blankText     : '未命名分类'
			});
			upperNode.treeEditor.on('beforecomplete', cataAction.renameCatalog, selModel);
        }            
        //@overrided
        ,findChild: function(nsIdNum){
        	var fn = $$.catalogTreeNode.superclass.findChild;
        	if(arguments.length >= 2){
            	return fn(arguments[0], arguments[1]);
        	}else{
        		return fn('ID', nsIdNum);
        	}
        }
    });
})();